<template>
  <div id="editor" />
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import E from 'wangeditor'
interface EmitsType {
  (e: 'update:model-value', val: string): void
}
const emit = defineEmits<EmitsType>()
const props = defineProps(({
  modelValue: {
    type: String,
    default: ''
  }
}))
const editor = ref<InstanceType <typeof E> | null>(null)
onMounted(() => {
  initEditor()
})
const initEditor = () => {
  editor.value = new E('#editor')
  // 配置 onchange 回调函数，修改数据后触发
  editor.value.config.onchange = function (newHtml: string) {
    console.log('change 之后最新的 html', newHtml)
    // 通过emit传递最新修改的值给父组件
    emit('update:model-value', newHtml)
  }
  editor.value.create()
}
const unWatch = watch(() => props.modelValue, (val, newVal) => {
  console.log(333)
  editor.value && editor.value.txt.html(props.modelValue) // 设置富文本的默认值，只需要执行一次就可
  // 监听一次后注销监听事件，
  unWatch()
})
</script>

<style lang="scss" scoped>
.content-space {
  display: flex;
  :deep(.content-space__item) {
    width: 100%;
  }
  :deep(.content-space__item:last-child) {
    padding-bottom: unset !important;
  }
}
</style>
